package com.yinhai.message.manage.register.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;

import javax.annotation.Resource;

import org.simplejavamail.MailException;
import org.springframework.stereotype.Controller;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RequestMapping;

import com.yinhai.core.app.api.util.ServiceLocator;
import com.yinhai.core.app.ta3.web.controller.BaseController;
import com.yinhai.core.common.api.base.IPage;
import com.yinhai.core.common.api.dto.IDto;
import com.yinhai.core.common.api.util.StringUtil;
import com.yinhai.core.common.ta3.dto.TaParamDto;
import com.yinhai.message.manage.register.bpo.IEmailConfigBpo;
import com.yinhai.message.manage.register.po.EmailConfigPo;
import com.yinhai.message.manage.register.vo.EmailConfigVo;
import com.yinhai.message.manage.sysapp.bpo.ISysAppBpo;
import com.yinhai.message.manage.sysapp.vo.SysAppVo;

/**
 * 邮箱配置Controller类
 * @author lanyc
 * 2017-1-5
 *
 */
@Controller
@RequestMapping("email")
public class EmailConfigController extends BaseController {
	/**
	 * 配置邮箱业务逻辑BPO接口
	 */
	@Resource
	private IEmailConfigBpo emailConfigBpo;
	
	/**
	 * 显示配置邮箱页面
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("EmailConfigController!configEmail.do")
    public String config() throws Exception {
		//刷新接入系统信息
		reFreshedEmailConfigs();
		return "manage/config/email/emailConfig";
	}
	
	@RequestMapping("EmailConfigController!pageQueryEmailConfig.do")
	public String queryAllEmailConfigByPage() throws Exception {
		TaParamDto dto = getTaDto();
		int start = dto.getStart("MainGrid");
		int limit = dto.getLimit("MainGrid");
		IPage page = emailConfigBpo.queryAllAccountsByPage(dto,start,limit,"MainGrid");
		setList("MainGrid",page);
		return JSON;
	}
	
	/**
	 * 查询全部邮箱配置信息
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("EmailConfigController!queryEmailConfigInfo.do")
	public String queryAllEmailConfig() throws Exception {
		//刷新接入系统信息
		reFreshedEmailConfigs();
		List<EmailConfigVo> list = emailConfigBpo.queryAllEmailConfig();
		setList("MainGrid",list);
		return JSON;
	}
	
	/**
	 * 保存邮箱配置信息
	 * @param emailConfigVo
	 * @return
	 */
	@RequestMapping("EmailConfigController!addEmailConfig.do")
    public String addEmailConfig(){
	    TaParamDto dto = getTaDto();
	    //将dto的信息封装为PO 
	    EmailConfigPo ecp = getEmailConfigPo(dto);
	    try{
	    	emailConfigBpo.addEmailConfig(ecp);
	    	setTopMsg("新增成功!");
	    	//将新增页面清空
	    	setData("emailAddress","");
	    	setData("password","");
	    	setData("sendHost","");
	    	setData("timeout","");
	    	setData("port","25");
	    	setData("isSendSSL",null);
	    	setData("isSendTLS",null);
	    	setData("defaultemail",null);
	    	List<SysAppVo> list = getUnDistrbutedSystem();
	    	List list1 = new ArrayList();
	    	setList("unDistrbutedSystem", list);
	    	setList("distrbutedSystem", list1);
	    }catch(MailException e){
	    	e.printStackTrace();
	    	setMessage("邮箱验证失败!请核对后重试!","error");
	    }
	    setEnable("btn_save");
		return JSON;
	}
	
	/**
	 * 根据前台传入的值准备EmailConfigPo对象
	 * @param dto
	 * @return
	 */
	private EmailConfigPo getEmailConfigPo(TaParamDto dto){
		EmailConfigPo ecp = new EmailConfigPo();
		ecp.setEmailAddress(dto.getAsString("emailAddress"));
		ecp.setPassword(dto.getAsString("password"));
		ecp.setPrefix(dto.getAsString("prefix"));
		ecp.setSendHost(dto.getAsString("sendHost"));
		ecp.setSendPort(Integer.parseInt(dto.getAsString("sendPort")));
		ecp.setTimeout(Integer.parseInt(dto.getAsString("timeout")));
	    
	    String isSendSSL = dto.getAsString("isSendSSL");
	    String isSendTLS = dto.getAsString("isSendTLS");
	    String defaultemail = dto.getAsString("defaultemail");
	    
	    //将isSendSSL和isSendTLS的值转换为整形值
	    if (isSendSSL!=null&&"ssl".equals(isSendSSL)) {
	    	ecp.setIsSendSSL(1);
		}else{
			ecp.setIsSendSSL(0);
		}
	    if (isSendTLS!=null&&"tls".equals(isSendTLS)) {
	    	ecp.setIsSendTLS(1);
		}else{
			ecp.setIsSendTLS(0);
		}
	    if (defaultemail!=null&&"dm".equals(defaultemail)) {
	    	ecp.setDefaultemail(1);
		}else{
			ecp.setDefaultemail(0);
		}
		//获取接入系统信息
		StringBuilder systemids = new StringBuilder();
		StringBuilder systemnames = new StringBuilder();
		StringBuilder sids = new StringBuilder();
		
		List<IDto> list = (List<IDto>) getGridSelected("distrbutedSystem");
		for (IDto iDto : list) {
			sids.append(iDto.getAsString("id")+",");
			systemids.append(iDto.getAsString("systemid")+",");
			systemnames.append(iDto.getAsString("systemname")+",");
		}
		ecp.setSid(sids.toString());
		ecp.setSystemId(systemids.toString());
		ecp.setSystemName(systemnames.toString());
		
		return ecp;
	}
	
	/**
	 * 保存邮箱配置信息
	 * @param emailConfigVo
	 * @return
	 */
	@RequestMapping("EmailConfigController!updateEmailConfig.do")
    public String updateEmailConfig(){
		TaParamDto dto = getTaDto();
		EmailConfigPo ecp = getEmailConfigPo(dto);
		try{
			emailConfigBpo.updateEmailConfigWithValidate(ecp);
			setTopMsg("修改成功!");
		}catch(MailException e){
	    	setMessage("邮箱验证失败!请核对后重试!","error");
	    }
		setEnable("btn_save");
		return JSON;
	}
	
	/**
	 * 邮箱账户验重
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("EmailConfigController!checkemailAddress.do")
    public String checkEmailAddress() throws Exception {
		TaParamDto dto = getTaDto();
		EmailConfigPo ecp = emailConfigBpo.queryEmailCfgByEmailAddress(dto.getAsString("emailAddress"));
		if (!ObjectUtils.isEmpty(ecp)) {
			setMessage("邮箱账户名已存在!","error");
			setData("emailAddress","");
		}
		
		return JSON;
	}
	
	/**
	 * 打开添加邮箱配置页面
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("EmailConfigController!toAddEmailConfig.do")
    public String toAddEmailConfig() throws Exception {
		reFreshedEmailConfigs();
		setList("unDistrbutedSystem", getUnDistrbutedSystem());
		return "manage/config/email/emailConfigAdd";
	}
	
	/**
	 * 获取未分配的接入系统
	 * @return
	 */
	private List<SysAppVo> getUnDistrbutedSystem(){
		ISysAppBpo sab = (ISysAppBpo) ServiceLocator.getService("sysAppBpo");
		List<SysAppVo> list = sab.getSysAppList();
		
		List<SysAppVo> SystemHasEmail = new ArrayList<SysAppVo>();
		for (SysAppVo sav : list) {
			if(StringUtil.isNotEmpty(sav.getSenderTypeOrder())){
				String[] types = sav.getSenderTypeOrder().trim().split(",");
				if(types.length>0){
					for (String s : types) {
						if("1".equals(s)){
							SystemHasEmail.add(sav);
							break;
						}
					}
				}
			}
		}
		List<EmailConfigVo> emailCfgs = emailConfigBpo.queryAllEmailConfig();
		HashSet<String> set = new HashSet<String>();
		for (EmailConfigVo ecv : emailCfgs) {
			if(ecv.getSystemId()==null){
				continue;
			}
			String[] systemids = ecv.getSystemId().trim().split(",");
			for (int i = 0; i < systemids.length; i++) {
				if(systemids[i]!=null){
					set.add(systemids[i]);
				}
			}
		}
		List<SysAppVo> unDistrubited = new ArrayList<SysAppVo>();
		for (SysAppVo sav : SystemHasEmail) {
			if(!set.contains(sav.getSystemid())){
				unDistrubited.add(sav);
			}
		}
		return unDistrubited;
	}
	
	/**
	 * 修改邮箱配置
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("EmailConfigController!toEditEmailConfig.do")
    public String toEditEmailConfig() throws Exception {
		reFreshedEmailConfigs();
		TaParamDto dto = getTaDto();
		EmailConfigPo ecp = emailConfigBpo.queryEmailCfgByEmailAddress(dto.getAsString("emailAddress"));
		
		setData("systemname",ecp.getSystemId());
		setData("emailAddress",ecp.getEmailAddress());
		setData("password",ecp.getPassword());
		setData("sendHost",ecp.getSendHost());
		setData("sendPort",ecp.getSendPort());
		setData("timeout",ecp.getTimeout());
		setData("prefix",ecp.getPrefix());
		
		if(ecp.getIsSendSSL()!=null&&ecp.getIsSendSSL().intValue()==1){
			setData("isSendSSL","ssl");
		}
		if(ecp.getIsSendTLS()!=null&&ecp.getIsSendTLS().intValue()==1){
			setData("isSendTLS","tls");
		}
		if(ecp.getDefaultemail()!=null&&ecp.getDefaultemail().intValue()==1){
			setData("defaultemail","dm");
		}
		//设置已分配到当前APP的接入系统
		if(StringUtil.isNotEmpty(ecp.getSystemId())&&StringUtil.isNotEmpty(ecp.getSystemName())){
			String[] ids = ecp.getSid().trim().split(",");
			String[] systemids = ecp.getSystemId().trim().split(",");
			String[] systemnames = ecp.getSystemName().trim().split(",");
			ArrayList<HashMap<String,String>> list = new ArrayList<HashMap<String,String>>();
			for (int i = 0; i < systemids.length; i++) {
				if(StringUtil.isNotEmpty(systemids[i])){
					HashMap<String,String> map = new HashMap<String,String>();
					map.put("id",ids[i]);
					map.put("systemid", systemids[i]);
					map.put("systemname", systemnames[i]);
					list.add(map);
				}
			}
			setList("distrbutedSystem", list);
		}
		//设置还未分配的系统
		setList("unDistrbutedSystem",getUnDistrbutedSystem());
		
		setReadOnly("emailAddress");
		return "manage/config/email/emailConfigEdit";
	}
	
	/**
	 * 删除邮箱信息
	 * @return
	 */
	@RequestMapping("EmailConfigController!deleteEmailInfo.do")
	public String deleteEmailInfo(){
		TaParamDto dto = getTaDto();
		emailConfigBpo.deleteEmailConfigInfo(dto.getAsString("emailAddress"));
		int start = dto.getStart("MainGrid");
		int limit = dto.getLimit("MainGrid");
		IPage<EmailConfigPo> page = emailConfigBpo.queryAllAccountsByPage(dto,start,limit,"MainGrid");
		setList("MainGrid",page);
		return JSON;
	}
	
	/**
	 * 由于接入系统可能会修改通信渠道，当其取消电子邮件后，邮件配置应该移除相应的接入系统
	 */
	private List<EmailConfigVo> reFreshedEmailConfigs(){
		List<EmailConfigVo> list = emailConfigBpo.queryAllEmailConfig();
		for (EmailConfigVo acv : list) {
			if(StringUtil.isNotEmpty(acv.getSid())){
				String[] sids = acv.getSid().trim().split(",");
				String[] systemIds = acv.getSystemId().trim().split(",");
				String[] systemNames = acv.getSystemName().trim().split(",");
				ISysAppBpo sab = (ISysAppBpo) ServiceLocator.getService("sysAppBpo");
				//查看该接入系统的通信渠道中是否有电子邮件
				for (int i=0;i<sids.length;i++) {
					SysAppVo sav = sab.getSysAppById(sids[i]);
					if(sav==null){
						sids[i]="";
						systemIds[i]="";
						systemNames[i]="";
					}else{
						String type = sav.getSenderTypeOrder();
						if(type==null||!(type.contains("1"))){
							sids[i]="";
							systemIds[i]="";
							systemNames[i]="";
						}
					}
					
				}
				//重新赋值
				StringBuilder sb = new StringBuilder();
				StringBuilder sb1 = new StringBuilder();
				StringBuilder sb2 = new StringBuilder();
				for (int i = 0; i < sids.length; i++) {
					if(sids[i]!=null&&sids[i]!=""){
						sb.append(sids[i]+",");
						sb1.append(systemIds[i]+",");
						sb2.append(systemNames[i]+",");
					}
				}
				//如果sid改变，说明有接入系统的通信渠道发生变化，则需要更新数据库
				if(!acv.getSid().equals(sb)){
					acv.setSid(sb.toString());
					acv.setSystemId(sb1.toString());
					acv.setSystemName(sb2.toString());
					
					EmailConfigPo acp = new EmailConfigPo();
					acp = acv.toPO(acp);
					emailConfigBpo.updateEmailConfig(acp);
				}
			}
		}
		return list;
	}
	
	/**
	 * 批量增加接入系统
	 */
	@RequestMapping("EmailConfigController!batchAddSystem.do")
	public String batchAddSystem(){
		TaParamDto dto = getTaDto();
		List s = getJsonStrToList(dto.getAsString("selected"));
		List all = getJsonStrToList(dto.getAsString("all"));
		List otherAll = getJsonStrToList(dto.getAsString("otherAll"));
		
		otherAll.addAll(s);
		all.removeAll(s);
		
		List forClear = new ArrayList();
		setList("distrbutedSystem", forClear);
		setList("unDistrbutedSystem", forClear);
		
		setList("distrbutedSystem", otherAll);
		setList("unDistrbutedSystem", all);
		return JSON;
	}
	
	/**
	 * 批量移除接入系统
	 */
	@RequestMapping("EmailConfigController!batchDeleteSystem.do")
	public String batchDeleteSystem(){
		TaParamDto dto = getTaDto();
		List s = getJsonStrToList(dto.getAsString("selected"));
		List all = getJsonStrToList(dto.getAsString("all"));
		List otherAll = getJsonStrToList(dto.getAsString("otherAll"));
		
		otherAll.addAll(s);
		all.removeAll(s);
		
		List forClear = new ArrayList();
		setList("distrbutedSystem", forClear);
		setList("unDistrbutedSystem", forClear);
		
		setList("distrbutedSystem", all);
		setList("unDistrbutedSystem", otherAll);
		return JSON;
	}
}
